package com.example.HelloSpace.viewmodels;

import android.content.Context;
import android.os.Bundle;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.Observer;

import com.example.HelloSpace.database.AppDatabase;
import com.example.HelloSpace.database.entities.SpaceMissionEntity;
import com.example.HelloSpace.models.ContentModel;
import com.example.HelloSpace.models.MissionInfoModel;
import com.example.HelloSpace.repository.MissionRepository;

import java.time.Instant;

public class MissionDetailsViewModel extends ViewModel {
    private final MissionRepository repository;
    private final LiveData<ContentModel> contentModelLiveData;
    private final MutableLiveData<Boolean> isSubscribed = new MutableLiveData<>();
    private Context context;

    public MissionDetailsViewModel(MissionRepository repository) {
        this.repository = repository;
        contentModelLiveData = repository.getMissionDetails(-1); // 初始化时传入无效ID
    }
    // 初始化加载数据并更新按钮状态
    public void loadSubscriptionStatus(long missionId) {
        LiveData<Boolean> result = repository.isMissionExists(missionId);
        result.observeForever(new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean exists) {
                isSubscribed.setValue(exists);
                result.removeObserver(this); // 确保只观察一次
            }
        });
    }

    public LiveData<ContentModel> getContentModelLiveData(int missionId) {
        return repository.getMissionDetails(missionId);
    }

    public void test(){
        repository.getSelectedMission().getValue().test();
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public LiveData<MissionInfoModel> getSelectedMission() {
        return repository.getSelectedMission();
    }
    public boolean saveSubscribedMission(MissionInfoModel missionInfoModel) {
        // 创建单个 SpaceMissionEntity 实例
        SpaceMissionEntity entity = new SpaceMissionEntity(
                missionInfoModel.getId(),
                missionInfoModel.getMissionName(),
                Instant.parse(missionInfoModel.getLaunchTimeUTC()) ,
                true,
                missionInfoModel.getLaunchTime(),
                missionInfoModel.getStatus()
        );
        return repository.saveSubscribedMission(entity);
    }
    public void cancelSubscribedMission(long missionId) {
        repository.cancelSubscribedMission(missionId);
    }
    // 获取按钮状态的LiveData
    public LiveData<Boolean> getIsSubscribed() {
        return isSubscribed;
    }
}
